package com.haojin.spring.jdbc;


import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

import java.util.List;

/**
 * @author .29.
 * @create 2023-02-06 19:34
 */

@SpringJUnitConfig(locations = "classpath:beans.xml")
public class JDBCTemplateTest {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //一、查询，返回对象
    @Test
    public void testSelectObject(){
        String sql = "select * from t_emp where id = ?";


        //方法一，手动封装对象(不推荐，麻烦)
        Emp empResult = jdbcTemplate.queryForObject(sql,((resultSet, i) -> {
            Emp emp = new Emp();
            emp.setId(resultSet.getInt("id"));
            emp.setName(resultSet.getString("name"));
            emp.setAge(resultSet.getInt("age"));
            emp.setSex(resultSet.getString("sex"));
            return emp;
        }),1);
        System.out.println(empResult);

        //方法二，直接调用方法封装对象 (new BeanPropertyRowMapper<>(Emp.class))
        Emp empResult2 = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(Emp.class),1);
        System.out.println(empResult2);
    }

    //二、查询，返回List集合
    @Test
    public void testSelectList(){
        String sql = "select * from t_emp";
        List<Emp> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Emp.class));
        System.out.println(list);
    }


    //三、查询，返回单个值
    @Test
    public void testSelectSingle(){
        String sql = "select count(*) from t_emp";
        Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
        System.out.println(count);
    }


    @Test
    public void testUpdate(){
        //1、添加操作
//        //第一步 编写sql语句
//        String sql = "insert into t_emp values(NULL,?,?,?);";
//
//        //第二步 调用jdbcTemplate的方法完成更新
//        int rows = jdbcTemplate.update(sql, "高启兰", 20, "女");//按顺序传入参数
//        /*也可通过数组传入参数
//        * Object[] params = {"高启强", 27, "男"}
//        * int rows = jdbcTemplate.update(sql,params);
//        * */
//        System.out.println("影响行数： "+rows);

        //2.删除操作
//        String sql = "delete from t_emp where id = ?";
//        int rows = jdbcTemplate.update(sql,2);
//        System.out.println(rows);

        //3.修改操作
//        String sql = "update t_emp set name = ? where id = ?";
//        int rows = jdbcTemplate.update(sql,"强盛集团老总",1);
//        System.out.println(rows);


    }
}

